package com.ms.oschina.adapter;

import java.util.ArrayList;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.ms.oschina.emoji.DisplayRules;
import com.ms.oschina.util.UiUtils;
import com.ms.oschina.view.ExpressionGridView;

public class ExpressionAdapter extends PagerAdapter {

	private OnExpressionSelectListener listener;

	/* 根据表情的类型判断有几页。 */
	public int getCount() {
		return 2;
	}

	// 3. 指定复用的判断逻辑, 固定写法
	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}

	// 1. 返回要显示的条目内容, 创建条目
	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		ExpressionGridView gridView = new ExpressionGridView(
				UiUtils.getContext());
		ArrayList<DisplayRules> disList = null;
		if (position == getCount() - 1) {// 添加所有类型
			disList = DisplayRules.getTypeList(position);
			disList.addAll(DisplayRules.getTypeList(position + 1));
		} else {
			disList = DisplayRules.getTypeList(position);
		}

		final ExpressionItemAdapter adapter = new ExpressionItemAdapter(gridView,
				disList);
		gridView.setAdapter(adapter);

		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				DisplayRules displayRules = adapter.getItem(position);
				listener.OnExpressionSelect(displayRules);
			}
		});
		container.addView(gridView);
		return gridView; // 必须重写, 否则报异常
	}

	// 2. 销毁条目
	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		container.removeView((View) object);
	}

	public ExpressionAdapter(OnExpressionSelectListener listener) {
		super();
		this.listener = listener;
	}

	public interface OnExpressionSelectListener {
		public abstract void OnExpressionSelect(DisplayRules displayRules);
	}
}
